import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 改变地址  /:id
  { path: '/detail/:id', component: () => import('@/views/Detail.vue') },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'article', component: () => import('@/views/Layout/Article.vue') },
      { path: 'collect', component: () => import('@/views/Layout/Collect.vue') },
      { path: 'like', component: () => import('@/views/Layout/Like.vue') },
      { path: 'user', component: () => import('@/views/Layout/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// // 全局导航守卫   1
// router.beforeEach((to, from, next) => {
//   if (to.path === '/login' || to.path === '/register') {
//   // 如果路径是登录或注册就next通过
//     next()
//   } else {
//   // 如果本地有token就可以访问通过，没有就返回登录页
//     if (localStorage.getItem('token')) {
//       next()
//     } else {
//       next('/login')
//     }
//   }
// })

const allow = ['/login', '/register']
router.beforeEach((to, from, next) => {
  if (allow.includes(to.path)) {
    // 判断allow数组中是否包含to.path,包含就通过
    next()
  } else {
    // 如果本地有token就可以访问通过，没有就返回登录页
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
